<template>
  <!-- action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" -->

  <el-upload
    v-model:file-list="picList"
    :action="uploadAction"
    :on-preview="handlePictureCardPreview"
    :show-file-list="showList"
    :on-remove="handleRemove"
    :before-upload="beforeUpload"
    :on-error="uploadError"
    :on-success="uploadSuccess"
    :data="uploadData"
    :multiple="true"
    list-type="picture"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { watchEffect } from 'vue'

// const fileList = ref<UploadUserFile[]>([
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'plant-1.png',
//     url: '/images/plant-1.png',
//   },
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'plant-2.png',
//     url: '/images/plant-2.png',
//   },
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'figure-1.png',
//     url: '/images/figure-1.png',
//   },
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'figure-2.png',
//     url: '/images/figure-2.png',
//   },
// ])

const props = defineProps({
  showList: {
    type: Boolean,
    default: () => {
      return true
    },
  },
  picList: {
    type: Array,
    default: () => {
      return []
    },
  },
  signConf: {
    type: String,
    default: () => {
      return ''
    },
  },
  tp: {
    type: Number,
    default: 1,
  },
  uploadData: {
    type: Object,
    default: () => {
      return {
        token: '',
      }
    },
  },
  picUrl: {
    type: String,
    default: () => {
      return ''
    },
  },
  bucket: {
    type: String,
    default: () => {
      return ''
    },
  },
  abled: {
    type: Boolean,
    default: () => {
      return false
    },
  },
  limit: {
    type: Number,
    default: 1,
  },
  text: {
    type: String,
    default: '只能上传jpg/png文件',
  },
  button: {
    type: String,
    default: '点击上传',
  },
})

// props.picList 写2
const { picList, signConf, picUrl } = props

//  ------------------------- 无用 -------------------------
// watch(
//   () => props.picList,
//   async (newImgs) => {
//     updatePicList(newImgs) // 调用回调函数更新props.picList
//     console.log('imgs属性发生变化:', picList)
//   },
// )

// const updatePicList = (newImgs) => {
//   emit('updateImg', newImgs) // 触发父组件传递的更新事件
// }
//  ------------------------- 无用 -------------------------

const uploadAction = 'https://upload.qiniup.com'
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

onMounted(() => {
  console.log('========onMounted======')
  console.log(picList)
})

const img = reactive<any>({
  fileName: '',
  width: 0,
  height: 0,
})

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

// 点击文件列表中已上传的文件时的钩子
const handlePictureCardPreview: UploadProps['onPreview'] = (picList) => {
  console.log('--------handlePictureCardPreview------')
  dialogImageUrl.value = picList.url!
  dialogVisible.value = true
}

function beforeUpload(file) {
  const isSize = new Promise(function (resolve, reject) {
    let _URL = window.URL || window.webkitURL
    let image = new Image()

    console.log('file-=-=-=-=-=')
    console.log(file)
    // {
    //   uid: 1739435456961
    //   lastModified:1699586299138
    //   lastModifiedDate: Fri Nov 10 2023 11:18:19 GMT+0800 (中国标准时间) {}
    //   name: "0007.jpeg"
    //   size: 122854
    //   type: "image/jpeg"
    //   webkitRelativePath: ""
    // }

    img.fileName = file.name
    // 获取图片款高
    image.onload = function () {
      img.width = image.width
      img.height = image.height
    }

    image.src = _URL.createObjectURL(file)
  }).then()

  const isPNG = file.type === 'image/png'
  const isJPEG = file.type === 'image/jpeg'
  const isJPG = file.type === 'image/jpg'

  if (!isPNG && !isJPEG && !isJPG) {
    ElMessage.error('上传头像图片只能是 jpg、png、jpeg 格式!')
    return false
  }
}

function uploadError(err, file, fileList) {
  ElMessage.error('上传出错，请刷新页面！')
  console.log(err)
}

// 定义一个数组
const imgList: { name: string; url: string; width: any; height: any }[] = []

function uploadSuccess(response) {
  console.log('--------response-----------')
  console.log(response)
  const timestamp = new Date().getTime()

  var pic = {
    name: timestamp + '/' + response.key, // 多个同时上传会被最后一个图片的名字覆盖，所以这里必须是自定义名称【除非单图】 同理 宽高一样，除非在这里直接请求 把数据发送到后端，后端返回id来保存【不建议】
    url: picUrl + '/' + response.key, // picUrl 是绑定的cdn域名
    width: img.width,
    height: img.height,
  }
  // var imgLet = [
  //   {
  //     name: img.fileName + '/' + response.key,
  //     url: picUrl + '/' + response.key, // picUrl 是绑定的cdn域名
  //     width: img.width,
  //     height: img.height,
  //   },
  // ]

  imgList.push(pic)

  console.log('s上传成功')
  setImgToF({ imgList: imgList, sign: signConf })
  // this.$emit('setImg', { imgList: img, sign: img.sign })
}

const emit = defineEmits(['setImg', 'updateImg'])
function setImgToF(obj: any) {
  // 2.将事件和状态传递给父组件
  emit('setImg', obj)
}
</script>
